import { request } from "../../request/index.js";
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';

// pages/user/index.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
    // 显示登录还是注册页面
		isLogin: true
	},

  // 改变显示登录和组成页面
	changeIsLogin (e) {
		const { login } = e.currentTarget.dataset
		if ( (login === 'login' && this.data.isLogin) || (login === 'register' && !this.data.isLogin)) return
		this.setData ({
				isLogin: !this.data.isLogin
		})
	},

  // 登录
  async form_login_submit (e) {
    const { userId, pwd } = e.detail.value
    if (userId.trim().length === 0) {
      wx.showToast({
        title: '用户名不能为空',
        icon: 'error',
        duration: 1500
      });
      return
    }
    if (pwd.trim().length === 0) {
      wx.showToast({
        title: '密码不能为空',
        icon: 'error',
        duration: 1500
      });
      return
    }
    const res = await request({
      url: '/user/login',
      method: 'POST',
      data: {
        pwd,
        userId
      }
    })
    if (res.resultTypeCode == 200) {
      wx.showToast({
        title: '登陆成功',
        icon: 'success',
        duration: 1500,
        success: ()=>{
          wx.setStorageSync("token", res.data);
          wx.setStorageSync("DDL", (Date.parse(new Date()) + 7 * 24 * 60 * 60 * 1000));
          wx.navigateBack({
            delta: 1
          }); 
        }
      })
    } else {
      wx.showToast({
        title: '账号或密码错误',
        icon: 'error',
        duration: 1500
      })
    }
  },

  // 注册
  async form_regsiter_submit (e) {
    const { userId, pwd, pwd_sure } = e.detail.value
    if (userId.trim().length === 0) {
      wx.showToast({
        title: '用户名不能为空',
        icon: 'error',
        duration: 1500
      });
      return
    }
    if (pwd.trim().length === 0) {
      wx.showToast({
        title: '密码不能为空',
        icon: 'error',
        duration: 1500
      });
      return
    }
    if (pwd_sure != pwd) {
      wx.showToast({
        title: '密码不一致',
        icon: 'error',
        duration: 1500
      });
      return
    }    
    const res = await request({
      url: '/user/register',
      method: "post",
      data: {
        pwd,
        userId
      }
    })
    console.log(res)
    if (res.resultTypeCode == 200) {
      wx.showToast({
        title: '注册成功',
        icon: 'success',
        duration: 1500,
        success: ()=>{
          wx.setStorageSync("token", res.data);
          wx.setStorageSync("DDL", ( + 7 * 24 * 60 * 60 * 1000));
          wx.navigateBack({
            delta: 1
          }); 
        }
      })
    } else {
      wx.showToast({
        title: '已存在该用户',
        icon: 'error',
        duration: 1500
      });
    }
  }
})